package de.alfenory.autobill.logic;

import de.alfenory.autobill.entity.*;
import java.util.*;

/**
 * @author alefen
 */
public class TaxTypeFacade {
    public static TaxType getTaxType(int id, List<TaxType> taxTypeList) {
        for(TaxType tt : taxTypeList) {
            if(tt.getId()==id) {
                return tt;
            }
        }
        return null;
    }
    
    public static double getTaxValue(TaxType tt, double value, Contact contact) {
        if(contact.isTaxFree()) {
            return 0;
        }
        if(contact.isTaxIncluded()) {
            double rate = tt.getVat()/100.0;
            int restValue = Math.abs(((int)(value*(1000))) % 10);
            double taxIncludedValue = ((int)(value*(100))) / 100.0;
            value = BookEntryFacade.round((value * 100 /(1.0+rate)) / 100.0);
            if(restValue >= 5 && value > 0) {
                taxIncludedValue += 0.01;
            }
            if(restValue >= 5 && value < 0) {
                taxIncludedValue -= 0.01;
            }
            
            if (Math.round((taxIncludedValue - 0.01) * 100.0 / 1.19) / 100.0 == taxIncludedValue) {
                taxIncludedValue = taxIncludedValue - 0.01;
            }
            return BookEntryFacade.round(taxIncludedValue - value);
        }
        else {
            double rate = tt.getVat()/100.0;
            value = BookEntryFacade.round(value);
            double taxIncludedValue = ((int)(value*(10000+rate*10000.0))) / 10000.0;
            return BookEntryFacade.round((taxIncludedValue - value)*100)/100.0;
        }
    }
}